//
// Created by hsj on 2024-1-11.
// 广播多播基于UDP;
// 直接广播：192.168.1.255
// 本地广播：255.255.255.255

#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <fcntl.h>

#ifdef WIN32
//windows minGW64
//inet_pton函数：_WIN32_WINNT
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#include <winsock2.h>
#include <ws2tcpip.h>
//#pragma comment(lib,"ws2_32.lib")
#else
//linux  gcc
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#endif
#define BUF_SIZE 30
void error_handling(char *buf);
int main(int argc,char *argv[]){
    int send_sock;
    struct sockaddr_in broad_adr;
    FILE *fp;
    char buf[BUF_SIZE];
    int so_brd=1;
    char ip[]="192.168.1.255";
    char port[]="4455";

    send_sock=socket(PF_INET, SOCK_DGRAM, 0);
    memset(&broad_adr, 0, sizeof(broad_adr));
    broad_adr.sin_family=AF_INET;
    broad_adr.sin_addr.s_addr=inet_addr(/*argv[1]*/ip);
    broad_adr.sin_port=htons(atoi(/*argv[2]*/port));
    setsockopt(send_sock, SOL_SOCKET,SO_BROADCAST, (void*)&so_brd, sizeof(so_brd));

    if((fp=fopen("news.txt", "r"))==NULL)
        error_handling( "fopen() error");

    while(!feof(fp))
    {
        fgets(buf, BUF_SIZE, fp);
        printf("%s\n",buf);
        sendto(send_sock, buf, strlen(buf),0, (struct sockaddr* )&broad_adr, sizeof(broad_adr));
        sleep(2);
    }
    fclose(fp);
    close(send_sock);

    return EXIT_SUCCESS;
}

void error_handling( char *message){
    fputs (message, stderr);
    fputc('\n', stderr);
    exit(1);
}